#!/usr/bin/env python
# -*- coding:utf-8 -*- 
# Author: MapzChen
# Email: 61966578@qq.co

from importlib import import_module
from django.conf import settings
SessionStore = import_module(settings.SESSION_ENGINE).SessionStore

class MStatus(object):
    def __init__(self,status_list,session,session_id,config):
        self.config = config
        self.session_key = session.session_key
        self.session_id = session_id
        self.session = SessionStore(session_key=self.session_key)
        self._status_str_list = status_list
        self._status_list = []
        self._status = {
            'on_progress': True,
            'process_end': False,
            'fail': False,
        }
        self.store = {

        }
        for s in self ._status_str_list:
            self._status_list.append({'name': s,'progress': 0 , 'out_put':[], 'done':False})

    #改变状态
    def update_status(self, status_name, progress):

        done = progress == 1
        index = self ._status_str_list.index(status_name)
        self._status_list[index]['done'] = done
        self._status_list[index]['progress'] = progress
        if index == len(self ._status_list) - 1 and progress == 1:
            self._status['on_progress'] = False
            self._status['process_end'] = True

        self.session[self.session_id] = self
        self.session.save()

    def end_with_fail(self,status_name):
        self._status['fail'] = True
        self._status['on_progress'] = False
        self._status['process_end'] = True


        self.session[self.session_id] = self
        self.session.save()


    # 增加输出
    def append_output(self,status_name,out_put):
        self._status_list[self ._status_str_list.index(status_name)]['out_put'].append(out_put)

        self.session[self.session_id] = self
        self.session.save()

    # 存储内容
    def setStore(self,**params):
        for i,k in params.items():
            self.store[i] = k

        self.session[self.session_id] = self
        self.session.save()

    def getStore(self,key):
        return self.store.get(key,None)

    def setFail(self):
        self._status['fail'] = True

        self.session[self.session_id] = self
        self.session.save()

    def setEnd(self):
        self._status['process_end'] = True

        self.session[self.session_id] = self
        self.session.save()

    def getStatus(self):
        return self._status

    def getStatusList(self):
        return self._status_list








